<!-- 支付页需要传一个对象 对象有以下属性
  title 标题
  palyImg 支付图片
  phone 电话号码--账号
  price 价格
  goodsId 商品id
 -->
<template>
  <view>
    <top-tabbar v-if="fromPary.platform && !appPlayState" tabTitle="确认订单" backColor="#ffffff" :titleStatus="true" @click="clickBack"></top-tabbar>
      <view class="popup-box">
        <view class="popup-main">
          <view class="order">
           <view class="order-img">
             <image style="border-radius: 20rpx;" mode="scaleToFill" :src="paryData.logoImageUrl"></image>
           </view>
           <view class="name-price">
             <view class="title-name">{{ paryData.name}}</view>
             <view class="price"><text class="RMB">￥</text>{{ paryData.price }}</view>
           </view>
          </view>
          <view class="from-item">
            <view class="pay-way">
              <view style="font-size: 28rpx;">支付方式</view>
              <view class="way-list">
                <view 
                  class="pay-wx-Alipay" 
                  v-for="(item,index) in payMethod" 
                  :key="item.id" 
                  v-if="$wechat.isWechat() ? index < 1: index<3"
                >
                  <view class="pay-name">
                    <view class="iconfont payIcon" :style="{color: item.color}">{{ item.icon }}</view>
                    <view class="pay-title">{{ item.name }}</view>
                  </view>
                   <radio-group @change="radioChange($event,item.id)">
                     <radio :value="index.toString()" :checked="index === current" color="#FF800C"/>
                    </radio-group>
                </view>
              </view>
            </view>
            <view class="item-from">
              <view class="asterisk"><text style="font-weight: normal;font-size: 30rpx;margin-right: 6rpx;">*</text>开通账号</view>
              <input
                class="phone-input" 
                placeholder="请输入手机号" 
                v-model="paryData.phone" 
                type="digit" 
                :maxlength="11"
                placeholder-style="font-size: 28rpx;color: #8C8C8C;text-align: right;"
              />
            </view>
            <view class="item-from">
              <view>优惠券</view>
              <view style="color: #8C8C8C;">无可用</view>
            </view>
            <view class="item-from" v-if="paryData.skuId == '03adfeca-ace2-87d5-3e9e-3a022c709a24'">
              <view class="activity-title">
                <view>活动</view>
                <view class="color-red">体验营专属</view>
              </view>
              <view>体验营限时特惠</view>
            </view>
          </view>
        </view>
        <view class="actually-paid"><text style="color: #333333;">实付：</text><text style="font-size: 36rpx;font-weight: bold;">￥{{ paryData.price }}</text></view>
        
        <view class="primary btn-zoom"  @click="verifyQuery">支付</view>
      </view>
  </view>
</template>

<script>
  import topTabbar from '@/components/topTabbar/index.vue'
  import luoButton from '@/components/botton/luo-botton.vue'
  import { squeezePage, wxSubmitOrder, wxH5pay, payHistory } from '@/utils/api.js'
  export default{
    components: { luoButton,topTabbar},
    data() {
      return{
        payState: 0,
        regPhone: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, // 手机正则
        pathUrl: '', // 地址参数
        billNo:'', // 订单单号
        appPlayState: false, // app跳来支付
        pagination: null, // 页码 
        domain: window.location.protocol+"//" + window.location.host, // 当前协议与域名
        current: 0, // 默认0
        payType: 1, // 支付类型1是微信，3是支付宝
        paryData:{ // 页面回显的参数
          name:'',
          price:'',
          skuId:'',
          logoImageUrl:'',
          phone:''
        },
        fromPary: {
          phone:'', // 手机号码
          skuId: '', // skuiD
          agentId: '' , // 需要传给支付渠道id
          rsid: '', // 子渠道id
          platform: '' ,// 客户端app所属平台
          staff:''
        },
        orderFrom: { // 订单参数
          address:{  phone:''},
          appName: 'shuidisw_web', // shuidisw_web默认是h5，shuidisw_mp是微信环境
          payType: '', // 1是微信支付，3是支付宝支付
          skus: [ { skuId: '', num: 1 } ],
          agentId: null ,// 渠道id
          staff: null // 所属商务id
        },
        payMethod: [
          { id: 1, name: '微信支付', icon: '\ueb06', color: '#4EED3A'},
          { id: 3, name: '支付宝支付', icon: '\ue688', color: '#34BAFF'}
        ]
      }
    },
    onLoad(params) {
      const vm = this
      if(window.location.href.split('?')[1]){
         vm.pathUrl = window.location.href.split('?')[1].toLowerCase()
      }
      if(vm.$auth.getUrlPrams("agentid") || vm.$auth.getUrlPrams("radid")){
        vm.orderFrom.agentId = vm.$auth.getUrlPrams("agentid") | vm.$auth.getUrlPrams("radid")
      }
      if(vm.$auth.getUrlPrams("staff")){
        vm.orderFrom.staff = vm.$auth.getUrlPrams("staff")
      }
      if(vm.$auth.getUrlPrams("phone")) {
        vm.paryData.phone = vm.$auth.getUrlPrams("phone")
      }
      if(params.platform) {
        let platform = params.platform.toLowerCase() // 转小写
        vm.fromPary.platform = platform
      }
      uni.removeStorageSync('appPlayState')
      if(vm.$auth.getUrlPrams("skuid")){
        this.getDetail(vm.$auth.getUrlPrams("skuid"))
        if(params.appPlayState == 1){
          this.appPlayState = true
          uni.setStorageSync("appPlayState",this.appPlayState)
        }
      }
       vm.$wechat.unseBehavior()
    },
    methods:{
      // 获取详情
      async getDetail(skuid,phone) {
        const vm = this
        const res = await squeezePage(skuid)
        vm.paryData.name = res.name
        vm.paryData.skuId = res.id
        vm.paryData.logoImageUrl = res.logoImageUrl
        vm.paryData.price = res.price
      },
      // 返回上一页
      clickBack() {
        uni.navigateBack({
          delta: 1
        })
      },
      // 单选框事件
      radioChange(e,id) {
        this.current = parseInt(e.detail.value)
        this.payType = id
      },
      // 验证与查询
      verifyQuery() {
        const vm = this
        if((new Date().getTime() - vm.payState ) > 2000) {
          vm.payState = new Date().getTime()
          if (!vm.paryData.phone){
            uni.showToast({  title:'请输入手机号码！', icon:'none' })          
            return false
          }
          if(vm.paryData.phone && !vm.regPhone.test(vm.paryData.phone)) {
            uni.showToast({  title:'手机号码格式不正确',icon:'none' })
            return false
          }
          payHistory(vm.paryData).then(res => {
            if(res.paidStatus){
              uni.showToast({  title:'您已经购买过该课程',icon:'none' }) 
            }else{
              vm.palyRightoff()
            }
          })
        }
      },
     /* 立即支付
      微信浏览器支付
      第一步要获取openid
      第二步用地址code获取opoenid
      第三步获取服务器订单
      第四步注入支付权限
      第五步调起支付 */
      async palyRightoff() {
        const vm = this
        // 创建订单--参数赋值
        vm.orderFrom.address.phone = vm.paryData.phone
        vm.orderFrom.payType = vm.payType
        vm.orderFrom.skus[0].skuId = vm.paryData.skuId
        if(vm.$wechat.isWechat()){
          vm.orderFrom.appName = 'shuidisw_mp'
          vm.orderFrom.openId = uni.getStorageSync('openId')
        }else{
          delete vm.orderFrom.openId
        }
        const orderData = await wxSubmitOrder(vm.orderFrom)
        if (!orderData) {
          return;
        }
        if (orderData.result.code !== 0) {
          uni.showToast({ title:orderData.result.message ,icon:'none' })
          return;
        }
          // 微信支付
          if(vm.payType === 1) {
            if(vm.$wechat.isEnterprise()){
              vm.getOrder(orderData)
              return;
            }
            if(vm.$wechat.isWechat()) {
              vm.$wechat.wxpay(orderData,
                sucess  => { // 成功
                  uni.navigateTo({
                    url: '/pages/add_account/addwx?phoneNumber='+vm.paryData.phone,
                  })
                  vm.payState= true
                },
                fail =>{ // 失败
                  uni.showToast({  title:'支付失败！',icon:'none' })
                  vm.payState= true
                },
                cancel  => { // 取消
                  uni.showToast({  title:'你已取消支付！',icon:'none' })
                  vm.payState= true
                }
              )
            }else{
              // h5微信支付
              vm.getOrder(orderData)
            }
          }
          // h5支付宝支付
          if(vm.payType === 3){
             vm.getOrder(orderData)
          }
      },
      // h5订单接口----vm.payType等于1是h5微信支付--等于3是支付宝支付
      async getOrder(orderData) {
        const vm = this
        let parameter = vm.domain+'/pages/my/order/payQuery?billNo='+orderData.billNo+'&phoneNumber='+vm.paryData.phone+'&skuid='+vm.paryData.skuId+'&platform='+vm.fromPary.platform+'&ver='+vm.$auth.getUrlPrams("ver")+'&agentid='+vm.orderFrom.agentId+'&staff='+vm.orderFrom.staff
       if (vm.payType === 3){
        uni.request({
            url: 'https://openapi.jinlinjishu.com/api/mall/alipay/pay/wap', 
            method:'POST',
            data: `amount=${orderData.amount}&billNo=${orderData.billNo}&appName=${orderData.appName}&description=${orderData.description}&quit_url=${encodeURIComponent(parameter)}&redirectUrl=${encodeURIComponent(parameter)}`,
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization': uni.getStorageSync('authorization'),
            },
            success: (res) => {
              // 将接口返回的Form表单显示到页面--调用submit 方法 
              // let div = document.createElement('div');
              // div.innerHTML = res.data;
              // document.body.appendChild(div)
              // document.forms[0].submit();
              document.querySelector('body').innerHTML = res.data;
              document.forms[0].submit()
            }
        })
       }
       // 微信h5支付
       if(vm.payType === 1) {
         const payWeb = await wxH5pay(orderData)
         if(payWeb.codeUrl) {
           let pathUrl = payWeb.codeUrl+'&redirect_url='+encodeURIComponent(parameter)
            window.location.replace(pathUrl)
         }
       }
      }
    }
  }
</script>

<style lang="scss" scoped>
  // 支付弹窗
  .popup-box{
    width: 100%;
    height: 100vh;
    background: #ffffff;
    padding: 32rpx  40rpx;
    padding-bottom: env(safe-area-inset-bottom);
    text-align: center;
    .popup-main{
      .order{
        display: flex;
        align-items: center;
        padding: 16rpx;
        background: #FFFAF5;
        border-radius: 20rpx;
        margin-bottom: 36rpx;
        .order-img{
          width: 176rpx;
          height: 176rpx;
        }
        .name-price{
          // width: 50%;
          // display: flex;
          // flex-direction: column;
          // justify-content: space-between;
          // align-items: end;
          text-align: left;
          margin-left: 32rpx;
          .main-title{
            font-size: 24rpx;
            color: #8C8C8C;
          }
          .title-name{
            font-weight: 500;
            font-size: 32rpx;
            color: #262626;
          }
          .price{
            color: #FE8512;
            font-size: 32rpx;
            font-weight: bold;
            margin-top: 40rpx;
          }
          .RMB{
            font-size: 24rpx;
          }
        }
      }
      .from-item{
        .pay-way{
          text-align: left;
          .way-list{
            width: 100%;
            height: auto;
            background: #F5FEFF;
            border-radius: 20rpx;
            margin-top: 18rpx;
            padding: 30rpx 18rpx 0 18rpx;
            .pay-wx-Alipay{
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding-bottom: 30rpx;
              .pay-name{
                display: flex;
                align-items: center;
                .payIcon{
                  font-size: 60rpx;
                }
                .pay-title{
                  margin-left: 10rpx;
                  font-size: 28rpx;
                  color: #262626;
                }
              }
              // 修改单选框样式
              uni-radio /deep/ .uni-radio-input{
                width: 32rpx !important;
                height: 32rpx !important;
                margin-right: 0 !important;
                border: 2rpx solid #FF800C !important;
              }
              uni-radio /deep/ .uni-radio-input.uni-radio-input-checked:before{
                font-size: 34rpx !important;
                 // -webkit-transform: translate(-50%,-48%)!important;
                // -webkit-transform: translate(-50%,-48%) scale(.6) !important;
              }
            }
          }
        }
        .item-from{
          width: 100%;
          height: 90rpx;
          border-bottom: 2rpx solid #eeeeee;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 28rpx;
          .asterisk{
            color: #FF3939;
            font-weight: bold;
          }
          .phone-input{
            text-align: right;
            font-size: 28rpx;
             color: #FF3939;
          }
          .activity-title{
            height: 90rpx;
            display: flex;
            align-items: center;
            color: #292929;
            .color-red{
              margin-left: 30rpx;
              background: #FFE7E7;
              font-size: 20rpx;
              padding: 4rpx 10rpx;
              border-radius: 8rpx;
              color: #FF3939;
            }
          }
        }
      }
    }
    .actually-paid{
      padding: 36rpx 0 72rpx 0;
      text-align: left;
      font-size: 28rpx;
      color: #FF840F;
    }   
    .primary{
      width: 680rpx;
      padding: 6rpx 0;
      border-radius: 44rpx;
      text-align: center;
      background: #FF800C;
      font-weight: bold;
      font-size: 48rpx;
      letter-spacing: 0.2em;
      color: #FFFFFF;
      position: fixed;
      left: 0;
      right: 0;
      bottom: 48rpx;
      margin: auto;
    }
  }
</style>
